package open.panxiong.shared.http.controller

import android.content.Context
import fi.iki.elonen.NanoHTTPD.IHTTPSession
import fi.iki.elonen.NanoHTTPD.Response
import open.panxiong.shared.http.annotation.NanohttpdApi
import open.panxiong.shared.http.config.ConstConfig
import open.panxiong.shared.http.model.NanohttpdResponse
import open.panxiong.shared.util.getDateString
import java.io.File
import java.io.FileOutputStream
import java.net.URLDecoder

class TextController {

    // 添加文本
    @NanohttpdApi("/api/add-text")
    fun addText(context: Context, session: IHTTPSession): Response {
        var content = session.parameters["content"]?.last()
        if (content.isNullOrEmpty()) {
            return NanohttpdResponse(code = -1, msg = "文本错误").toJson()
        }
        content = URLDecoder.decode(content, Charsets.UTF_8.name())
        val dir = ConstConfig.getSharedFileDirectory(context)
        val name = if (content.length > 5) {
            content.substring(0, 5) + "_" + getDateString() + ".txt"
        } else {
            content + "_" + getDateString() + ".txt"
        }

        FileOutputStream(File(dir, name)).use { outputStream ->
            outputStream.write(content.toByteArray())
            outputStream.flush()
        }

        return NanohttpdResponse(data = name).toJson()
    }

}